<!-- 3D地图组件 -->
<template>
  <div ref="mapContainer" class="h-[800px] w-full relative">
    <div v-if="error" class="absolute top-0 left-0 bg-red-100 p-2 text-red-600 text-sm">
      {{ error }}
    </div>
    <!-- 模型切换下拉框 -->
    <div class="absolute top-4 right-4 z-10 flex items-center space-x-2 bg-white bg-opacity-80 p-2 rounded shadow">
      <label for="model-select" class="mr-2 text-sm text-gray-700">选择模型：</label>
      <select id="model-select" v-model="currentModel" @change="onModelChange" class="px-2 py-1 rounded border border-gray-300">
        <option v-for="item in modelList" :key="item.key" :value="item.key">
          {{ item.name }}
        </option>
      </select>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as Cesium from 'cesium'

const mapContainer = ref<HTMLElement>()
const error = ref<string>('')
let viewer: Cesium.Viewer | null = null

// ====== 模型列表配置 ======
// 后续如需添加更多模型，只需在 modelList 里添加一项，并在 modelParams 里补充参数即可
const modelList = [
  { key: 'model1', name: '模型1' },
  { key: 'model2', name: '模型2' },
  { key: 'model3', name: '模型3' }, // ← 示例：添加更多模型
] as const

type ModelKey = typeof modelList[number]['key']

const currentModel = ref<ModelKey>('model1')

// 所有模型的参数配置，key 要和 modelList 里的 key 一致
const modelParams: Record<ModelKey, { assetId: number; modelMatrix: Cesium.Matrix4 }> = {
  model1: {
    //法门寺
    assetId: 3353811,
    modelMatrix: (() => {
      const position = Cesium.Cartesian3.fromDegrees(107.8953, 34.4455, 105)
      const originalModelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position)
      const scale = new Cesium.Cartesian3(300, 300, 300)
      const scaleMatrix = Cesium.Matrix4.fromScale(scale)
      return Cesium.Matrix4.multiply(originalModelMatrix, scaleMatrix, new Cesium.Matrix4())
    })()
  },
  model2: {
    //测试古风楼
    assetId: 3350260,
    modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
      Cesium.Cartesian3.fromDegrees(114.592, 36.659664, 5)
    )
  },
  model3: {
    //岐山周公庙
    assetId: 3357242,
    // modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
    //   Cesium.Cartesian3.fromDegrees(107.604878,34.493538, 5))
    modelMatrix: (() => {
      const position = Cesium.Cartesian3.fromDegrees(107.6005,34.494, 18)
      const originalModelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position)
      const scale = new Cesium.Cartesian3(100, 100, 100)
      const scaleMatrix = Cesium.Matrix4.fromScale(scale)
      return Cesium.Matrix4.multiply(originalModelMatrix, scaleMatrix, new Cesium.Matrix4())
    })()
  }
  // model3: { assetId: ..., modelMatrix: ... }, // ← 示例：添加更多模型参数
}

// 切换模型时重新创建 tileset
const showModel = async (model: string) => {
  if (!viewer) return
  viewer.scene.primitives.removeAll()
  const { assetId, modelMatrix } = modelParams[model as ModelKey]
  const tileset = await Cesium.Cesium3DTileset.fromIonAssetId(assetId, { modelMatrix })
  viewer.scene.primitives.add(tileset)
  await viewer.zoomTo(tileset)
  // 样式（仅对 model1 设置）
  if (model === 'model1') {
    const extras = tileset.asset.extras
    if (
      Cesium.defined(extras) &&
      Cesium.defined(extras.ion) &&
      Cesium.defined(extras.ion.defaultStyle)
    ) {
      tileset.style = new Cesium.Cesium3DTileStyle(extras.ion.defaultStyle)
    }
  }
}

const onModelChange = async () => {
  await showModel(currentModel.value)
}

const initMap = async () => {
  try {
    if (!mapContainer.value) {
      error.value = '地图容器未找到'
      return
    }

    console.log('开始初始化3D地图...')

    // 配置Cesium token
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmOGY0MDg0ZS0xYTY1LTQ2MTAtYjZmMC05ODFlZTFkYzVlY2MiLCJpZCI6Mjc0MDUwLCJpYXQiOjE3Mzg4OTc5Mjd9.Q82VUx1nRn8k1s8m2ZDrtSuqScleBBJnxt1QskbSpp0'

    // 创建viewer实例
    viewer = new Cesium.Viewer(mapContainer.value, {
      baseLayerPicker: true,
      timeline: false,
      animation: false,
      navigationHelpButton: false,
      homeButton: false,
      sceneModePicker: false,
      geocoder: false,
      fullscreenButton: false,
      infoBox: false,
      selectionIndicator: false,
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: false
        }
      }
    })

    console.log('创建viewer实例成功')

    // 移除默认的影像图层
    // viewer.imageryLayers.removeAll()

    // 添加高德矢量地图
    const gaodeLayer = new Cesium.UrlTemplateImageryProvider({
      url: 'https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      minimumLevel: 1,
      maximumLevel: 18
    })
    // viewer.imageryLayers.addImageryProvider(gaodeLayer)

    console.log('添加高德地图图层成功')

    // 默认展示模型1
    await showModel(currentModel.value)

    // 移除版权信息
    const creditContainer = viewer.cesiumWidget.creditContainer as HTMLElement
    creditContainer.style.display = 'none'

    // 设置默认视角为宝鸡市中心
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(107.1742, 34.3697, 50000),
      orientation: {
        heading: Cesium.Math.toRadians(0.0),
        pitch: Cesium.Math.toRadians(-45.0),
        roll: 0.0
      }
    });

    // 启用深度检测
    viewer.scene.globe.enableLighting = false
    viewer.scene.globe.depthTestAgainstTerrain = true
    viewer.scene.globe.showGroundAtmosphere = false
    viewer.scene.skyBox.show = false
    viewer.scene.sun.show = false
    viewer.scene.moon.show = false
    viewer.scene.fog.enabled = false
    
    console.log('3D地图初始化完成')
  } catch (e) {
    console.error('3D地图初始化失败:', e)
    error.value = `初始化失败: ${e instanceof Error ? e.message : String(e)}`
  }
}

onMounted(() => {
  console.log('Map3D组件已挂载')
  initMap()
})

onBeforeUnmount(async () => {
  console.log('正在销毁3D地图...')
  if (viewer) {
    viewer.scene.primitives.removeAll()
    viewer.destroy()
    viewer = null
    await new Promise(r => setTimeout(r, 100)) // 给销毁留时间，避免阻塞
  }
})
</script>

<style>
/* 确保Cesium容器样式正确 */
.cesium-viewer {
  position: absolute !important;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 100% !important;
}

.cesium-viewer-cesiumWidgetContainer {
  width: 100%;
  height: 100%;
}

.cesium-widget, .cesium-widget canvas {
  width: 100% !important;
  height: 100% !important;
}

/* 隐藏Cesium的logo和水印 */
.cesium-viewer-bottom {
  display: none !important;
}

/* 隐藏搜索框、热门分类和快捷操作框 */
.cesium-viewer-toolbar,
.cesium-viewer-animationContainer,
.cesium-viewer-timelineContainer,
.cesium-viewer-baseLayerPickerContainer {
  display: none !important;
}

/* 确保地图容器有正确的尺寸 */
/*.h-[500px] {
  min-height: 500px;
}*/
</style>